import { reqAddressList, reqDelAddress } from '../../../api/address'
import { modal } from '../../../../../utils/extendApi'
import { swiperCellBehavior } from '../../../../../behaviors/swiperCell'

const app = getApp()

Page({
  behaviors: [swiperCellBehavior],
  // 页面的初始数据
  data: {
    addressList: []
  },

  async getAddressList() {
    const { data: addressList } = await reqAddressList()
    this.setData({
      addressList
    })
  },
  onShow() {
    this.getAddressList()
  },
  // 去编辑页面
  toEdit(event) {
    const { id } = event.currentTarget.dataset

    wx.navigateTo({
      url: `/modules/settingModule/pages/address/add/index?id=${id}`
    })
  },
  async delAddress(event) {
    const { id } = event.currentTarget.dataset
    const modalRes = await modal({
      content: '您确定要删除吗？'
    })
    if (!modalRes) return
    await reqDelAddress(id)
    this.getAddressList()
  },
  onLoad(options) {
    if (options.flag) this.flag = options.flag
  },
  changeAddress(event) {
    if (this.flag !== '1') return
    const address = this.data.addressList.find(
      (item) => item.id === event.currentTarget.dataset.id
    )
    if (address !== {}) {
      app.globalData.address = address
      wx.navigateBack()
    }
  }
})
